package com.nacos.config.configuration;

import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.listener.Listener;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingService;

import java.io.IOException;
import java.util.Properties;
import java.util.concurrent.Executor;

/**
 * @author chn
 * @Feature: 带监听器的获取配置
 * @data 2024/9/12 14:16
 * @version 1.0
 */
public class getConfigurationWithListener {
    public static void main(String[] args) throws NacosException, IOException {
        try {
            Properties properties = new Properties();
            properties.put("serverAddr", "localhost:8848");
            properties.put("username", "nacos");
            properties.put("password", "nacos");

            ConfigService configService = NacosFactory.createConfigService(properties);
            NamingService namingService = NacosFactory.createNamingService(properties);
            // 配置监听
            Listener listener = new Listener() {

                @Override
                public void receiveConfigInfo(String configInfo) {
                    System.out.println("当前配置为：" + "\n" + configInfo);
                }

                @Override
                public Executor getExecutor() {
                    return null;
                }
            };

            String configAndSignListener = configService.getConfigAndSignListener("application.yml", "DEFAULT_GROUP", 10000, listener);
            System.out.println(configAndSignListener);

            // 持续监听，时间间隔为一秒
            while (true) {
                Thread.sleep(1000);
            }
        } catch (NacosException | InterruptedException e){
            e.printStackTrace();
        }

    }
}
